package com.attendance.controller;

import com.attendance.Utils.Converter.TypeConverter;
import com.attendance.Utils.PaginationUtil;
import com.attendance.model.Form.TypeForm;
import com.attendance.model.Result.Response;
import com.attendance.model.Result.ResultCode;
import com.attendance.model.Type;
import com.attendance.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Inuyasha on 2016/12/1.
 */
@RestController
@RequestMapping("/type")
public class TypeController {

    @Autowired
    private ITypeService typeService;

    @RequestMapping(value = "",method = RequestMethod.GET)
    public Response getAll(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int rows,
                           @RequestParam(defaultValue = "id") String sort, @RequestParam(defaultValue = "asc") String order,
                           @ModelAttribute TypeForm typeForm){
        Response response = new Response();
        PaginationUtil.preset(page, rows, sort, order);
        Type type = TypeConverter.convert(typeForm);
        List<Type> list = typeService.getAll(type);
        response.putResult(list);
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    public Response add(@ModelAttribute TypeForm typeForm){
        Response response = new Response();
        try {
            Type type = TypeConverter.convert(typeForm);
            typeService.insertSelective(type);
        } catch (Exception e) {
            return new Response(ResultCode.TYPE_ADD_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.DELETE)
    public Response delete(@ModelAttribute TypeForm typeForm){
        Response response = new Response();
        try {
            Type type = TypeConverter.convert(typeForm);
            typeService.deleteById(type.getId());
        } catch (Exception e) {
            return new Response(ResultCode.TYPE_DELETE_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.PUT)
    public Response update(@ModelAttribute TypeForm typeForm){
        Response response = new Response();
        try {
            Type type = TypeConverter.convert(typeForm);
            typeService.updateSelectiveById(type);
        } catch (Exception e) {
            return new Response(ResultCode.TYPE_UPDATE_ERROR);
        }
        return response;
    }
}
